package pl.pw.mkmw.pnganimator.file;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import pl.pw.mkmw.pnganimator.exception.ChunkNotInitializedException;
import pl.pw.mkmw.pnganimator.exception.PngAnimatorException;
import pl.pw.mkmw.pnganimator.image.DataCompressor;
import pl.pw.mkmw.pnganimator.image.SImage;
import pl.pw.mkmw.pnganimator.image.chunks.FileSignature;
import pl.pw.mkmw.pnganimator.image.chunks.IDATChunk;
import pl.pw.mkmw.pnganimator.image.chunks.IENDChunk;
import pl.pw.mkmw.pnganimator.image.chunks.IHDRChunk;
import pl.pw.mkmw.pnganimator.image.chunks.xDATChunk;
import pl.pw.mkmw.pnganimator.image.filter.Filter;
import pl.pw.mkmw.pnganimator.utils.ByteArrayUtils;

/**
 *
 * @author MK
 */
public class FileComposer {

    private static final Logger LOG = Logger.getLogger(FileComposer.class.getName());

    public byte[] generateFile(List<SImage> frames) throws PngAnimatorException {
        LOG.log(Level.INFO, "generateFile");

        //first frame for now

        SImage first = frames.get(0);

        byte[] result;
        try {
            //File Signature & IHDR
            IHDRChunk iHDRChunk = new IHDRChunk(first.getWidth(), first.getHeight(), IHDRChunk.BitDepth.EIGHT);
            iHDRChunk.setColourType(IHDRChunk.ColourType.TRUECOLOUR_ALPHA);
            result = ByteArrayUtils.concate(FileSignature.getSig(), iHDRChunk.getChunk());

            //IDAT
            byte[] deflated = DataCompressor.deflate(first);
            IDATChunk iDATChunk = new IDATChunk(deflated);
            result = ByteArrayUtils.concate(result, iDATChunk.getChunk());


            //xDATs
            Filter f = new Filter();
            List<SImage> filteredFrames = f.filterSimpleFuture(frames);
            for (int i = 1; i < filteredFrames.size(); i++) {
                deflated = DataCompressor.deflate(filteredFrames.get(i));
                xDATChunk xDATChunk = new xDATChunk(deflated);
                result = ByteArrayUtils.concate(result, xDATChunk.getChunk());
            }

            //IEND
            IENDChunk iENDChunk = new IENDChunk();
            result = ByteArrayUtils.concate(result, iENDChunk.getChunk());

            return result;
        } catch (ChunkNotInitializedException e) {
            LOG.log(Level.WARNING, "Chunk was not initialized");
            throw new PngAnimatorException();
        }

    }
}
